from flask import Blueprint, render_template, request, redirect, url_for, session, jsonify

from ext import db
# 导入用户表数据模型
from model.user import User
from datetime import datetime
# 导入加密函数
from utils.util import md5
import json

from werkzeug.utils import secure_filename
import os

bp = Blueprint('user', __name__, url_prefix='/user')


@bp.route('/')
def index():
    # 获取登录用户用户数据
    login_user_id = session.get('login_user_id')
    user = User.query.get(login_user_id)
    # 获取当前用户发布的文章
    # 获取当前日期
    curr_datetime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    data = {
        "title": "个人中心",
        "datetime": curr_datetime,
        "user": user
    }
    # 如果没有登录,自动跳转到登录页面
    if session.get('is_login') is None:
        return redirect(url_for('user.login'))
    else:
        return render_template('user/index.html', data=data)


# 文件上传
@bp.route('/upload', methods=['GET', 'POST'])
def upload():
    print(request.files, 'files')
    if 'avatar' not in request.files:
        return 'No file part'
        # return redirect(url_for('user.index'))

    file = request.files['avatar']
    if file.filename == '':
        return 'No selected file'
        # return redirect(url_for('user.index'))
    if file:
        filename = secure_filename(file.filename)
        file.save(os.path.join('uploads', filename))
        # return f'<h1>File uploaded successfully: {filename}</h1>'
        return redirect(url_for('user.index'))


# 账号注册

@bp.route('/register', methods=['GET', 'POST'])
def register():
    data = {
        "title": "账号注册"
    }
    if request.method == 'GET':
        return render_template('user/register.html', data=data)
    else:
        # 获取表单参数
        username = request.form.get('username')
        password = request.form.get('password')
        password2 = request.form.get('password2')
        if password != password2:
            data['error'] = '两次密码输入不一致'
            return render_template('user/register.html', data=data)
        # 执行注册流程
        user = User(username=username, password=md5(password))
        db.session.add(user)
        db.session.commit()
        return redirect(url_for('user.login'))


@bp.route('/login', methods=['GET', 'POST'])
def login():
    data = {
        "title": "账号登录"
    }
    if request.method == 'GET':
        return render_template('user/login.html', data=data)
    else:
        # request.form: 获取表单数据x-www-form-urlencoded
        # request.json: 获取json数据
        # 获取表单数据:post数据
        username = request.form.get('username')
        password = request.form.get('password')
        # 查询账号是否存在
        result = User.query.filter(User.username == username).first()
        # result是一个User类的实例对象, 所以不能通过[]方式获取属性,必须通过.方式访问属性
        # 只有dict字典和list列表才可以通过[]方式访问属性
        if result and result.password == md5(password):
            session['is_login'] = True
            # 记录登录账号id
            session['login_user_id'] = result.id
            # 记录登录用户信息: 先将实例对象转换为dict字典类型,再将其转换为json字符串类型
            # user_dict=result.to_dict()
            # session['login_user_info'] = json.dumps(user_dict)
            return redirect(url_for('user.index'))
        else:
            # 通过[]方式更新字典属性, .方式容易报错
            data['error'] = '账号或者密码错误'
            return render_template('user/login.html', data=data)


@bp.route('/logout')
def logout():
    # 删除登录session
    session.pop('is_login', None)
    # 自动跳转到登录页面
    return redirect(url_for('user.login'))


@bp.route('/json')
def json():
    output = {
        'code': 200,
        'msg': 'ok'
    }
    # 将字典转换为json字符串返回
    return jsonify(output)
